const express = require('express');
const { User } = require('../db/models');
const dayjs = require('dayjs');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const { auth } = require('../middlewares/Auth');
const { pageNation } = require('../middlewares/Page');
const { uploadFunc } = require('../upload/index');
const { Access } = require('../utils/Access');
const multer = require('multer');
const upload = multer();

const SECRET = 'TOKEN_SECRET';

const app = express.Router();

app.use(express.json());

app.use(Access)

app.get('/random/:min/:max',(req,res) => {
	const TIME = dayjs().valueOf();
	const TIME_FORMAT = dayjs().format('YYYY-MM-DD HH:mm:ss:SSS');
	const min = parseInt(req.params.min);
	const max = parseInt(req.params.max);
	if(isNaN(min) || isNaN(max)){
		res.status(400);
		res.json({ error:'bad request' });
		return;
	}
	const result = Math.round(Math.random() * (max - min) + min);
	const returnObj = {
		result,
		TIME,
		TIME_FORMAT
	};
	res.json(returnObj);
});
/***
 * 注册
 */
app.post('/register',async (req,res) => {
	
	try {
		const { username,password } = req.body;
		const user = await User.create({
			username,
			password
		});
		return res.status(200).send({...user,success:true,message:'注册成功'});
	}catch(e){
		console.log('e',e)
	}
	
});
/***
 * 登录给出token
 */
app.post('/login',async (req,res) => {
	const users = await User.findOne({
		username:req.body.username
	});
	if(!users){
		return res.status(422).send({ message:'用户名不存在',success:false });
	}
	const isPasswordValid = bcrypt.compareSync(req.body.password,users.password);
	if(!isPasswordValid){
		return res.status(422).send({ message:'密码错误',success:false });
	}
	const token = jwt.sign(
		{
			id:String(users._id)
		},
		SECRET,
		{
			expiresIn:60 * 60 * 24 * 7
		}
	);
	
	return res.send({ message:'登录成功',success:true,token });
});

app.get('/users',auth,async (req,res) => {
	res.send(req.userInfo);
});

app.get('/users/list',auth,async (req,res) => {
	const users = await User.find();
	res.status(200).send({ success:true,message:'查詢成功',data:users });
});

app.get('/users/listPage',auth,pageNation,async (req,res) => {
	const { pageNo = 1,pageSize = 10 } = req.page;
	const skip = (pageNo - 1) * pageSize;
	const { pageNo:n,pageSize:s,...reset } = req.body;
	const users = await User.find(reset || {}).skip(skip).limit(pageSize);
	const total = await User.find(reset || {}).countDocuments();
	res.status(200).send({ success:true,message:'查詢成功',data:users,pageNo,pageSize,total });
});

app.post('/upload',upload.single('fileUpload'),uploadFunc);

module.exports = app;
